package mj.scott.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import mj.scott.pojo.entity.User;
import mj.scott.mapper.UserMapper;
import mj.scott.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户信息 服务实现类
 * @author Scott
 * @since 2025-08-15
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据openid获取用户：不存在则自动创建
     */
    public User getOrCreateUser(String openid) {
        // 1. 查询是否存在该openid的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        User user = userMapper.selectOne(queryWrapper);

        // 2. 不存在则创建新用户
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now()); // 自动填充创建时间
            userMapper.insert(user); // 插入后自动生成id
            // 重新查询获取完整用户信息（含自增id）
            user = userMapper.selectOne(queryWrapper);
        }
        return user;
    }

    /**
     * 更新用户信息（如昵称、头像）
     */
    public void updateUser(User user) {
        userMapper.updateById(user);
    }
}

